<template>
  <div class="text-center">
    <div class="text-lg mb-2">欢迎登录</div>
    <div class="mb-4">请输入用户名密码用以登录</div>
    <div class=" max-w-[450px] w-4/5 mx-auto">
      <a-input class=" !mb-2" size="large" v-model:value.trim="info.phone" placeholder="请输入您的用户名，默认为您的手机号码" />
      <div class=" relative">
        <a-input-password class=" !mb-2" size="large" v-model:value.trim="info.password"
          placeholder="请输入您的密码"></a-input-password>
        <a @click="emits('setType', 'resetPassword')"
          class=" z-20  absolute leading-9 w-20 right-8 text-default">忘记密码?</a>
      </div>
      <button @click="submit" class="!my-6 w-full bg-base text-white outline-none">登 录</button>
      <div>还没有账号？请<a class="ml-1" @click="emits('setType', 'register')">注册</a></div>
    </div>
  </div>
</template>

<script lang='ts' setup>
import { login } from '@/request/api'
import route from '@/router/index'
import manage from '@/router/manage'
import { encrypt } from '@/utils/crypto'
import { message } from 'ant-design-vue'
import CryptoJS from 'crypto-js'
import Cookies from 'js-cookie'
const router = useRouter()
const info = reactive<{ phone: string; password: string }>({
  phone: '',
  password: '',
})
const emits = defineEmits(['setType'])
const submit = () => {
  if (
    !/^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/.test(
      info.phone.trim()
    )
  ) {
    message.error('手机号码格式不正确，请确认后再发送！')
  } else if (!info.password.trim()) {
    message.error('密码不可为空！')
  } else {
    login({
      ...info,
      password: CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(info.password))))
    }).then((res) => {
      const response = res
      if (res.code == 200) {
        new Promise((resolve, reject) => {
          const info = encrypt(JSON.stringify(res.result))
          Cookies.set('info', info, { expires: 14 })
          resolve(true)
        }).then((res) => {
          if (response.result.admin) {
            route.addRoute(manage)
          }
          router.push({ path: '/' })
        })
      }
    })
  }
}
</script>